let Local = function() {
    //游戏对象
    let game;
    //时间间隔
    let INTERVAL = 500;
    //定时器
    let timer = null;
    //时间计数器
    let timeCount = 0;
    //时间
    let time = 0;

    //计时
    let timeFunc = function() {
        timeCount = timeCount + 1;
        if(timeCount == (1000 / INTERVAL)) {
            timeCount = 0;
            time = time + 1;
            game.setTime(time);
        }
    }

    //绑定键盘事件
    let bindKeyEvent = function() {
        document.onkeydown = function(event) {
            let e = event || window.event; //获取event对象
            if(e.keyCode == 38) {
                //up
                game.rotate();
            } else if (e.keyCode == 39) {
                //right
                game.right();
            } else if (e.keyCode == 40) {
                //down
                game.down();
            } else if (e.keyCode == 37) {
                //left
                game.left();
            } else if (e.keyCode == 32) {
                //space
                game.fall();
            }
        }
    }
    //方块种类
    let generateType = function() {
        return Math.ceil(Math.random() * 4) -1;
    }
    //方向
    let generateDir = function () {
        return Math.ceil(Math.random() * 3) - 1;
    }

    //移动
    let move = function() {
        timeFunc();
        if(!game.down()) {
            game.fixed();
            let line = game.checkClear();
            if(line) {
                game.addScore(line);
            }
            if(game.checkGameOver()) {
                game.gameOver(false);
                stop();
            } else{
                game.performNext(generateType(), generateDir());
            }
        }

    }
    //开始
    let start = function() {
        let doms = {
            gameDiv: document.getElementById('game'),
            nextDiv: document.getElementById('next'),
            timeDiv: document.getElementById('time'),
            scoreDiv: document.getElementById('score'),
            resultDiv: document.getElementById('resultDiv')
        }
        game = new Game();
        game.init(doms, generateType(), generateDir());
        bindKeyEvent();
        game.performNext(generateType(), generateDir());
        timer = setInterval(move, INTERVAL);
    }

    //结束
    let stop = function() {
        if(timer) {
            clearInterval(timer);
            timer = null;
        }
        document.onkeydown = null;
    }

    //导出API
    this.start = start;
}
